package com.tamir.template.util;

import com.alibaba.fastjson.JSONObject;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : tanggh
 * @description :〈描述〉
 * @date : 2017/1/9
 */
public class YamlUtil
{
    /**
     * 解析yaml配置文件
     * @param fileName
     * @return
     */
    public static Map parseYaml(String fileName){
        if(StringUtil.isEmpty(fileName)){
            return null;
        }
        int pos = fileName.lastIndexOf(".");
        String fileType = pos == -1?"" : fileName.substring(pos+1);
        fileType = fileType.toLowerCase();
        if(!fileType.toLowerCase().equals("yaml") && !fileType.toLowerCase().equals
                ("yml")){
            throw new RuntimeException("Type of configuration file  must be pattern the yaml or " +
                    "yml " +
                    "format");
        }
        String classpath = YamlUtil.class.getResource(File.separator).getPath();
        String path = classpath + File.separator + "test.yaml";
        File dumpFile=new File(path);
        Yaml yaml = new Yaml();
        Map yamlObject = null;
        try
        {
            yamlObject = yaml.loadAs(new FileInputStream(dumpFile), HashMap.class);
        }
        catch (FileNotFoundException e)
        {
            throw new RuntimeException(e);
        }
        System.out.println(JSONObject.toJSONString(yamlObject));
        return yamlObject;
    }

    public static void main(String[] args)
    {
        YamlUtil.parseYaml("test.yaml");
    }
}
